package com.example.expresshelp.service;

import java.util.ArrayList;
import java.util.List;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.util.Log;

import com.example.expresshelp.bean.Address;
import com.example.expresshelp.bean.City;
import com.example.expresshelp.bean.District;
import com.example.expresshelp.bean.Province;
import com.example.expresshelp.bean.Towntr;
import com.example.expresshelp.bean.Villagetr;
import com.example.expresshelp.db.MySqliteHelper;
import com.example.expresshelp.util.Constance;
import com.example.expresshelp.util.HttpClientHelper;
import com.example.expresshelp.util.Validator;

/**
 * 镇
 * 
 * @author josan_tang
 * 
 */
public class TowntrService {
	private static final String TAG = "TowntrService";

	/**
	 * 解析信息
	 * 
	 */
	public static List<Towntr> parseTowntr(Context context, String pCode,
			String cCode, String did, String dCode, String html) {
		List<Towntr> towntrList = new ArrayList<Towntr>();
		String resultHtml = HttpClientHelper.doPost(html, null, 0);
		if (!Validator.isEffective(resultHtml)) {
			return null;
		}
		Document document = Jsoup.parse(resultHtml);
		Elements districtRows = document.getElementsByClass("towntr");

		for (int i = 0; i < districtRows.size(); i++) {
			Towntr towntr = new Towntr();
			Element tr = districtRows.get(i);
			Elements tds = tr.getElementsByTag("td");
			// 第一个td里是超链接没和城市代码
			Element codeTd = tds.get(0);
			Element codeA = codeTd.getElementsByTag("a").get(0);
			String hrefHtml = codeA.attr("href");
			// 110101中的最后一个01
			String allCode = codeA.text();
			String tCode = allCode.substring(6, 9);
			// 第二个td里面有名称
			Element nameTd = tds.get(1);
			Element nameA = nameTd.getElementsByTag("a").get(0);
			String towntrName = nameA.text();
			Log.i("express", "towntr - >" + tCode + towntrName);
			long tid = saveToDB(context, did, tCode, towntrName);
			/*String VillagetrUrl = Constance.BASE_URL + pCode + "/" + cCode
					+ "/" + hrefHtml;
			List<Villagetr> villagetrList = VillagetrService
					.parseVillagetr(context, pCode, cCode, dCode, tid + "",
							tCode, VillagetrUrl);*/
			towntr.setId(tid + "");
			towntr.setDid(did);
			towntr.setDistrictCode(dCode);
			towntr.setCode(tCode);
			towntr.setName(towntrName);
			//towntr.setVillagetrList(villagetrList);
			towntrList.add(towntr);
		}
		return towntrList;

	}

	/**
	 * 把信息保存到数据库中
	 * 
	 * @param context
	 * @param code
	 * @param name
	 */
	public static long saveToDB(Context context, String dCode,
			String towntrCode, String towntrName) {
		try {
			// 构造参数
			ContentValues values = new ContentValues();
			values.put("dcode", dCode);
			values.put("code", towntrCode);
			values.put("name", towntrName);
			return MySqliteHelper.getInstance(context).insert(
					Constance.TOWNTR_TABLE_NMAE, null, values);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return 0;
	}

	/**
	 * 
	 * @param context
	 * @param code
	 * @return
	 */
	public static List<Towntr> getTowntrByDistrictcode(Context context,
			String dCode) {
		List<Towntr> list = null;
		String where = " dcode=" + dCode;
		Cursor cursor = MySqliteHelper.getInstance(context).query(
				Constance.TOWNTR_TABLE_NMAE, where);
		if (cursor != null) {
			list = new ArrayList<Towntr>();
			while (cursor.moveToNext()) {
				Towntr towntr = new Towntr();
				towntr.setDistrictCode(dCode);
				towntr.setCode(cursor.getString(cursor.getColumnIndex("code")));
				towntr.setName(cursor.getString(cursor.getColumnIndex("name")));
				list.add(towntr);
			}
		}
		return list;
	}

	/**
	 * 
	 * @param context
	 * @param code
	 * @return
	 */
	public static Towntr find(Context context, String tid) {
		Towntr towntr = null;
		String where = " id='" + tid + "'";
		Cursor cursor = MySqliteHelper.getInstance(context).query(
				Constance.TOWNTR_TABLE_NMAE, where);
		if (cursor != null) {
			while (cursor.moveToNext()) {
				towntr = new Towntr();
				towntr.setId(cursor.getString(cursor.getColumnIndex("id")));
				towntr.setDid(cursor.getString(cursor.getColumnIndex("dcode")));
				towntr.setCode(cursor.getString(cursor.getColumnIndex("code")));
				towntr.setName(cursor.getString(cursor.getColumnIndex("name")));
			}
		}
		return towntr;
	}

	/**
	 * 
	 * @param context
	 * @param code
	 * @return
	 */
	public static Towntr findAll(Context context) {
		Towntr towntr = null;
		String where = " 1=1 ";
		Cursor cursor = MySqliteHelper.getInstance(context).query(
				Constance.TOWNTR_TABLE_NMAE, where);
		if (cursor != null) {
			while (cursor.moveToNext()) {
				towntr = new Towntr();
				towntr.setId(cursor.getString(cursor.getColumnIndex("id")));
				towntr.setDistrictCode(cursor.getString(cursor
						.getColumnIndex("dcode")));
				towntr.setCode(cursor.getString(cursor.getColumnIndex("code")));
				towntr.setName(cursor.getString(cursor.getColumnIndex("name")));
				Log.i("express", "towntr->" + towntr.getId() + towntr.getName());
			}
		}
		return towntr;
	}

	/**
	 * 
	 * @param context
	 * @param code
	 * @return
	 */
	public static List<Address> getTowntrByName(Context context, String name) {
		List<Address> addressList = null;
		List<Towntr> list = null;
		String where = " name like '%" + name + "%'";
		Cursor cursor = MySqliteHelper.getInstance(context).query(
				Constance.TOWNTR_TABLE_NMAE, where);
		if (cursor != null) {
			list = new ArrayList<Towntr>();
			addressList = new ArrayList<Address>();
			while (cursor.moveToNext()) {
				Towntr towntr = new Towntr();
				Address address = new Address();

				
				String dcode = cursor.getString(cursor.getColumnIndex("dcode"));
				towntr.setDid(dcode);
				towntr.setCode(cursor.getString(cursor.getColumnIndex("code")));
				towntr.setName(cursor.getString(cursor.getColumnIndex("name")));
				list.add(towntr);
				address.setFilterAddress(towntr.getName());
				StringBuffer totalAddress = new StringBuffer();
				District district = DistrictService.find(context,
						towntr.getDid());
				if (district != null) {
					totalAddress.append(",");
					totalAddress.append(district.getName());
					City city = CityService.find(context, district.getCid());
					if (city != null) {
						String cityName = city.getName();
						if (!(cityName.equals("市辖区") || cityName.equals("县"))) {
							totalAddress.append(",");
							totalAddress.append(city.getName());
						}
						Province province = ProvinceService.find(context,
								city.getPid());
						if (province != null) {
							totalAddress.append(",");
							totalAddress.append(province.getName());
						}
					}
				}
				address.setUnfilterAddress(totalAddress.toString());
				addressList.add(address);
			}
		}
		return addressList;
	}
}
